package com.defysoft.waukids.diary;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseFragment;
import com.defysoft.waukids.Custom_Data_Type.Diary_Main_List;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.main.Main_MainFrame;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Diary_Main_F extends BaseFragment {
	View view;
	ListView listView;
	ImageView writeview;
	public Diary_Main_Adapter adapter;
	ArrayList<Diary_Main_List> list;
	TextView nodata;
	private final int SUCCESSGETPLUSLIST = 7;
	private final int STARTDETAIL = 8;
	private final int NODATA = 9;
	private final int SUCCESSGETLIST = 10;
	private final int NODATA_PLUS = 6;	
	DisplayImageOptions options;
	ImageLoader imageLoader;
	Calendar calendar;
	int rank = 0;
	int selectCode = 0;
	long now = System.currentTimeMillis();
	Date date = new Date(now);
	Sqlite_Connect sc;
	SimpleDateFormat CurYearFormat ;
	SimpleDateFormat CurMonthFormat ;
	SimpleDateFormat CurDayFormat ;
	SimpleDateFormat CurHourFormat ;
	SimpleDateFormat CurMinuteFormat ;
	SimpleDateFormat CurSecondFormat ;
	int count = 0;
	boolean ListViewLock;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.diary_main_fragment, null);
		setStartData();

		return view;
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		CurYearFormat = new SimpleDateFormat("yyyy");
		CurMonthFormat = new SimpleDateFormat("MM"); 
		CurDayFormat = new SimpleDateFormat("dd");   
		CurHourFormat = new SimpleDateFormat("HH");  
		CurMinuteFormat = new SimpleDateFormat("mm");
		CurSecondFormat = new SimpleDateFormat("ss");
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getActivity()).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app

				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();
		imageLoader.clearMemoryCache();
		imageLoader.clearDiskCache();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
		/* .imageScaleType(ImageScaleType.EXACTLY) */
		.cacheOnDisk(true).considerExifParams(true).build();
		rank = Integer.parseInt(((Main_MainFrame) getActivity()).member.Rank);
		sc = ((Main_MainFrame) getActivity()).sqlite_Connect;
		writeview = (ImageView) view.findViewById(R.id.diary_main_item_write);
		if (rank == 2) {
			writeview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					((Main_MainFrame) getActivity()).startForActivity(
							START_DIARY, new Intent(getActivity(),
									Diary_Main_Write.class));

				}
			});

		} else {
			writeview.setVisibility(View.GONE);
		}

		nodata = (TextView) view.findViewById(R.id.diary_main_item_nodata);
		listView = (ListView) view.findViewById(R.id.diary_main_item_list);
		listView.setDivider(null);
		nodata.setVisibility(View.GONE);
		startNetwork(1);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				case 3:
					plusThread();
					break;
				}
			}
		});
		firstThread.start();
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			listView.setVisibility(View.VISIBLE);
			((Main_MainFrame)getActivity()).sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Diary_Main_F", ((Main_MainFrame)getActivity()).member.Email);
			break;
		case NODATA:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			listView.setVisibility(View.GONE);
			nodata.setVisibility(View.VISIBLE);
			break;
		case NODATA_PLUS:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(getActivity(), ((String)_message.obj), Toast.LENGTH_LONG).show();
			break;
		case SUCCESSGETLIST:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			nodata.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			adapter = new Diary_Main_Adapter();
			listView.setAdapter(adapter);
			listView.setOnScrollListener(new OnScrollListener() {

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub

					int lastItem = totalItemCount - visibleItemCount;
					if (firstVisibleItem >= lastItem && totalItemCount != 0
							&& ListViewLock == false) {
						if (list.size() < count) {
							ListViewLock = true;
							startNetwork(3);
						}
					}

				}
			});
			break;
		case STARTDETAIL:

			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			adapter.notifyDataSetChanged();
			((Main_MainFrame) getActivity()).startForActivity(START_DIARY,
					new Intent(getActivity(), DiaryDetailActivity.class)
							.putExtra("PK_Dia_Code",
									list.get(selectCode).PK_Dia_Code));
			break;
		case SUCCESSGETPLUSLIST:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			adapter.notifyDataSetChanged();
			ListViewLock = false;
			break;
		}
	}

	public void mainThread() {
		String msg = "";
		JSONObject jsonObject;
		try {
			if (rank == 1) {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_DIARY_MAIN_GETLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School));
			} else if (rank == 2) {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_DIARY_MAIN_GETLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School
										+ "&class="
										+ ((Main_MainFrame) getActivity()).member.Class));
			} else {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_DIARY_MAIN_GETLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School
										+ "&class="
										+ ((Main_MainFrame) getActivity()).student.Class
										+ "&stu="
										+ ((Main_MainFrame) getActivity()).student.Code));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				count = Integer.parseInt(jsonObject.getString("count"));
				list = JsonParser.Diary_Main_List_Parser(msg);
				onNetworkCallback(SUCCESSGETLIST, "");
			} else {
				onNetworkCallback(NODATA, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where mainThread()");
		}
		;
	}

	public void subThread() {
		sc.delete_New_Diary(Integer.parseInt(list.get(selectCode).PK_Dia_Code));
		if (rank == 3) {
			//새로운글 sqlite에서 삭제
			if (sc.check_Diary(
					Integer.parseInt(list.get(selectCode).PK_Dia_Code),
					Integer.parseInt(((Main_MainFrame) getActivity()).student.Code))) {
				onNetworkCallback(STARTDETAIL, "");
			} else {
				try {
					JSONObject jsonObject = new JSONObject(publicHttpCallback(
							HTTP_URL, "code=" + CODE_DIARY_MAIN_UPRATE + "&pk="
									+ list.get(selectCode).PK_Dia_Code
									+ "&uprate=" + 1));
					if (jsonObject.getBoolean("success")) {
					//조회수 추가
						sc.insert_Diary(
								Integer.parseInt(list.get(selectCode).PK_Dia_Code),
								Integer.parseInt(((Main_MainFrame) getActivity()).student.Code));
						list.get(selectCode).Dia_Rate = (Integer.parseInt(list
								.get(selectCode).Dia_Rate) + 1) + "";
						onNetworkCallback(STARTDETAIL, "");
					} else {
						onNetworkCallback(STARTDETAIL, "");
					}
				} catch (Exception e) {
					onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where subThread()");
				}
			}
		} else {
			onNetworkCallback(STARTDETAIL, "");

		}
	}

	public void plusThread() {
		String msg = "";
		JSONObject jsonObject;
		try {
			if (rank == 1) {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ 
										CODE_DIARY_MAIN_GETPLUSLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School
										+ "&pk="
										+ list.get(list.size() - 1).PK_Dia_Code));
			} else if (rank == 2) {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ 
										CODE_DIARY_MAIN_GETPLUSLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School
										+ "&class="
										+ ((Main_MainFrame) getActivity()).member.Class
										+ "&pk="
										+ list.get(list.size() - 1).PK_Dia_Code));
			} else {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ 
										CODE_DIARY_MAIN_GETPLUSLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School
										+ "&class="
										+ ((Main_MainFrame) getActivity()).student.Class
										+ "&stu="
										+ ((Main_MainFrame) getActivity()).student.Code
										+ "&pk="
										+ list.get(list.size() - 1).PK_Dia_Code));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				list.addAll(JsonParser.Diary_Main_List_Parser(msg));
				onNetworkCallback(SUCCESSGETPLUSLIST, "");
			} else {
				onNetworkCallback(NODATA_PLUS, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where plusThread()");
		}
		;
	}

	public class Diary_Main_Adapter extends ArrayAdapter<String> {

		public Diary_Main_Adapter() {
			super(getActivity(), 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Diary_Main_Holder holder;
			final int pos = position;
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.diary_main_fragment_item, null);
				holder = new Diary_Main_Holder();
				holder.title = (TextView)convertView.findViewById(R.id.diary_main_item_title);
				holder.sub = (TextView) convertView
						.findViewById(R.id.diary_main_item_sub);
				holder.schoolname = (TextView) convertView
						.findViewById(R.id.diary_main_item_school);
				holder.pretime = (TextView) convertView
						.findViewById(R.id.diary_main_item_time);
				holder.rate = (TextView) convertView
						.findViewById(R.id.diary_main_item_rate);
				holder.viewPager = (ViewPager) convertView
						.findViewById(R.id.diary_main_item_pager);
				holder.newiv = (ImageView) convertView
						.findViewById(R.id.diary_main_item_new);
				holder.sub_two = (TextView) convertView
						.findViewById(R.id.diary_main_item_sub_two);
				/*holder.stamp = (ImageView) convertView
						.findViewById(R.id.diary_main_item_stamp);*/
				
				convertView.setTag(holder);
			} else {
				holder = (Diary_Main_Holder) convertView.getTag();
			}
			//새로운글 체크
			   if (((Main_MainFrame) getActivity()).student != null) {
		            if (sc.check_New_Diary(
		                  Integer.parseInt(list.get(pos).PK_Dia_Code),
		                  Integer.parseInt(((Main_MainFrame) getActivity()).student.Code))) {
		               holder.newiv.setVisibility(View.VISIBLE);
		            } else {
		               holder.newiv.setVisibility(View.GONE);
		            }
		         }else{
		        	 if (sc.check_New_Diary(
			                  Integer.parseInt(list.get(pos).PK_Dia_Code),0)) {
			               holder.newiv.setVisibility(View.VISIBLE);
			            } else {
			               holder.newiv.setVisibility(View.GONE);
			            }		        	 
		         }
			holder.title.setText(list.get(position).Dia_Name);
			holder.sub.setText(list.get(position).Dia_Sub);
			if (rank == 1 || rank == 2) {
				holder.schoolname.setText(list.get(position).Sendname
						+ "의 원아수첩");
			} else {
				
				holder.schoolname
				.setText(list.get(position).Dia_Writer);
				/*if (list.get(position).Teacher.equals("null")
						|| list.get(position).Teacher.equals("")) {
					holder.schoolname
							.setText(((Main_MainFrame) getActivity()).school.Name
									+ " 원장님");
				} else {
					holder.schoolname.setText(list.get(position).Teacher
							+ " 선생님");
				}*/
			}
			/*holder.stamp.setVisibility(View.VISIBLE);
			//스탬프 3종류.
			if (list.get(pos).Dia_Stamp.equals("1")) {
				holder.stamp.setBackgroundResource(R.drawable.stamp_one);
			} else if(list.get(pos).Dia_Stamp.equals("2")){
				holder.stamp.setBackgroundResource(R.drawable.stamp_two);
			} else if(list.get(pos).Dia_Stamp.equals("3")){
				holder.stamp.setBackgroundResource(R.drawable.stamp_three);
			} else {
				holder.stamp.setVisibility(View.INVISIBLE);
			}*/
			holder.pretime
					.setText(timeCalculation(list.get(position).Dia_Date));

			holder.rate.setText(list.get(position).rev_count);

			if (list.get(position).photo.size() != 0) {
				holder.sub_two.setVisibility(View.VISIBLE);
				RelativeLayout.LayoutParams viewpagetParams = new RelativeLayout.LayoutParams(
						view.getWidth(), view.getWidth()
								- ((int) getResources().getDimension(
										R.dimen.viewpagertopmarjin) * 2));
				viewpagetParams.addRule(RelativeLayout.BELOW,
						holder.sub.getId());
				holder.viewPager.setLayoutParams(viewpagetParams);
				
				RelativeLayout.LayoutParams textpagetParams = new RelativeLayout.LayoutParams(
						view.getWidth()- ((int) getResources().getDimension(R.dimen.textmarjin)*2 )
						, view.getWidth()- ((int) getResources().getDimension(R.dimen.textmarjin)*3 )
								);
				textpagetParams.addRule(RelativeLayout.BELOW,
						holder.sub.getId());
				textpagetParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
				holder.sub_two.setLayoutParams(textpagetParams);
				
				holder.viewPager.setAdapter(new PagerAdapter() {

					@Override
					public int getCount() {
						return list.get(pos).photo.size();
					}

					@Override
					public Object instantiateItem(View pager, int positions) {
						View v = null;

						v = getActivity().getLayoutInflater().inflate(
								R.layout.diary_main_fragment_item_image, null);
						((ViewPager) pager).addView(v, 0);
						imageLoader.displayImage(
								HTTP_URL_DIARYPHOTO
										+ list.get(pos).photo.get(positions).Dia_Pho_IMG,
								(ImageView) v
										.findViewById(R.id.diary_main_fragment_img),
								options, null);
						((ImageView) v
								.findViewById(R.id.diary_main_fragment_img)).setOnClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										selectCode = pos;
										startNetwork(2);
									}
								});
						return v;
					}

					@Override
					public void destroyItem(View pager, int position,
							Object view) {
						((ViewPager) pager).removeView((View) view);
					}

					@Override
					public boolean isViewFromObject(View pager, Object obj) {
						return pager == obj;
					}

					@Override
					public void restoreState(Parcelable arg0, ClassLoader arg1) {
					}

					@Override
					public Parcelable saveState() {
						return null;
					}

					@Override
					public void startUpdate(View arg0) {
					}

					@Override
					public void finishUpdate(View arg0) {
					}

				});
				holder.viewPager.setClipToPadding(false);
			} else {
				holder.sub_two.setVisibility(View.GONE);
				RelativeLayout.LayoutParams viewpagetParams = new RelativeLayout.LayoutParams(
						0, 0);

				viewpagetParams.addRule(RelativeLayout.BELOW,
						holder.sub.getId());
				holder.viewPager.setLayoutParams(viewpagetParams);
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					selectCode = pos;
					startNetwork(2);
				}
			});
			return convertView;
		}

	}

	protected String timeCalculation(String data) {
		// 시간 계산기. split
		String diary_date = data;
		String result = "";
		// 1.공지사항 시간.
		String dia_date = diary_date.split(" ")[0];
		String dia_time = diary_date.split(" ")[1];
		// 일월년 분할.
		int dia_year = Integer.parseInt(dia_date.split("-")[0]);
		int dia_month = Integer.parseInt(dia_date.split("-")[1]);
		int dia_day = Integer.parseInt(dia_date.split("-")[2]);
		// 시분초 분할.
		int dia_hour = Integer.parseInt(dia_time.split(":")[0]);
		int dia_minute = Integer.parseInt(dia_time.split(":")[1]);
		int dia_second = Integer.parseInt(dia_time.split(":")[2]);

		// 2. 현재날짜시간
		int now_year = Integer.parseInt(CurYearFormat.format(date));
		int now_month = Integer.parseInt(CurMonthFormat.format(date));
		int now_day = Integer.parseInt(CurDayFormat.format(date));
		int now_hour = Integer.parseInt(CurHourFormat.format(date));
		int now_minute = Integer.parseInt(CurMinuteFormat.format(date));
		int now_second = Integer.parseInt(CurSecondFormat.format(date));

		// 3. 계산기 시작.
		if (dia_year < now_year) {
			result = dia_date;
		} else if (dia_month < now_month) {
			int a = (now_month - dia_month);
			result = a + " 개월 전";
		} else if (dia_day < now_day) {
			int aa = (now_day - dia_day);
			result = aa + " 일 전";
		} else if (dia_hour < now_hour) {
			int aaa = (now_hour - dia_hour);
			result = aaa + " 시간 전";
		} else if (dia_minute < now_minute) {
			int aaaa = (now_minute - dia_minute);
			result = aaaa + " 분 전";
		} else if (dia_minute == now_minute) {
			result = "방금 전";
		} else {
			result = "방금 전";
		}
		// 계산기 끝.
		/** 하단 미확인부모, 스탬프3개 */
		return result;
	}

	class Diary_Main_Holder {
		TextView title;
		ViewPager viewPager;
		TextView schoolname;
		TextView pretime;
		TextView sub;
		TextView rate;
		TextView sub_two;
		ImageView newiv;
		ImageView stamp;
		
	}

}
